/**
 * SpringMVC restful 风格
 * 云市场控制器，控制关于云市场的一些业务逻辑操作
 * @author yanwl
 * @date 2014-08-20
 */
package com.chnbst.bstyun.controller.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.controller.CheckEmail;
import com.chnbst.bstyun.core.common.DESUtil;
import com.chnbst.bstyun.core.common.email.EmailUtil;
import com.chnbst.bstyun.model.pojo.CompanyIndustry;
import com.chnbst.bstyun.model.pojo.CompanyScale;
import com.chnbst.bstyun.model.pojo.Email;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.Menu;
import com.chnbst.bstyun.model.pojo.Province;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.service.CompanyIndustryService;
import com.chnbst.bstyun.service.CompanyScaleService;
import com.chnbst.bstyun.service.DredgeUserService;
import com.chnbst.bstyun.service.EmailService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.MenuService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PlaceService;
import com.chnbst.bstyun.service.UserService;
//import com.chnbst.mail.EmailUtil;

@Controller
@RequestMapping("/dredge")
public class DredgeController {
	
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private MenuService menuService;
	@Autowired
	private DredgeUserService dredgeUserService;
	@Autowired
	private UserService userService;
	@Autowired
	private CompanyIndustryService companyIndustryService;
	@Autowired
	private CompanyScaleService companyScaleService;
	@Autowired
	private PlaceService placeService;
	@Resource 
	private TaskExecutor taskExecutor;//注入Spring封装的异步执行器
	@Autowired
	private OrderService orderService;
	@Autowired
	private EmailService emailService;
	
	@Autowired
	private GoodsService goodsService;
	
	private static final String ROLE_COMPANY = "ROLE_COMPANY";//公司用户
	private static final String ROLE_PERSON = "ROLE_PERSON";//个人用户
	private static final String ROLE_AGENT = "ROLE_AGENT";//代理商
	/**
	 * MC标准服务平台协议
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/openMCDeal", method = RequestMethod.GET)
	public ModelAndView openMCDeal() throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("dredge/mcdeal");
		return modelAndView;
	}
	
	/**
	 * http://xxx.com/dredge/{goodsId}/{useYear}/{userNum}
	 * 设置域名第一步
	 */
	@RequestMapping(value="/{goodsId}/{useYear}/{userNum}/{shoppingCartId}",method=RequestMethod.GET)
	public ModelAndView dredge(@PathVariable String goodsId,@PathVariable Integer useYear,
			@PathVariable Integer userNum,@PathVariable Integer shoppingCartId,HttpServletRequest request){
		// 菜单显示
		List<Menu> menus = menuService.selectMenus();
		// 公司所属行业
		List<CompanyIndustry> companyIndustries = companyIndustryService.selectCompanyIndustries();
		// 公司规模
		List<CompanyScale> companyScales = companyScaleService.selectCompanyScales();
		// 地区联动
		List<Province> provinceList = placeService.getProvinceList();
		
		//查询商品的信息
//		GoodsVo goodsVo = goodsService.selectGoodsVoByGoodsId(goodsId);
		
		ModelAndView mav = new ModelAndView();
		
		mav.addObject("shoppingCartId", shoppingCartId);
		mav.addObject("useYear",useYear);
		mav.addObject("userNum",userNum);
		mav.addObject("goodsId", goodsId);
		mav.addObject("menus", menus);
		mav.addObject("companyIndustries", companyIndustries);
		mav.addObject("companyScales", companyScales);
		mav.addObject("provinceList",provinceList);
		mav.setViewName("dredge/dredge");
		return mav;
	}
	
	/**
	 * http://xxx.com/dredge/dredgeNext/{domain}/{newUserId}/{goodsId}/{useYear}/{userNum}
	 * get请求 返回开通界面
	 * @throws Exception 
	 */
	@RequestMapping(value="/dredgeNext/{domain}/{newUserId}/{goodsId}/{useYear}/{userNum}/{shoppingCartId}",method=RequestMethod.GET)
	public ModelAndView dredgeNext(@PathVariable String domain,@PathVariable Integer newUserId,
			@PathVariable String goodsId,@PathVariable Integer useYear,@PathVariable Integer userNum,@PathVariable Integer shoppingCartId) throws Exception{
		/**
		 * 菜单显示
		 */
		List<Menu> menus = menuService.selectMenus();

		ModelAndView mav = new ModelAndView();
		mav.addObject("menus", menus);
		mav.addObject("userId", newUserId);
		mav.addObject("domain", "admin@"+domain);
		mav.addObject("goodsId",goodsId);
		mav.addObject("useYear",useYear);
		mav.addObject("userNum",userNum);
		mav.setViewName("dredge/setinfo");
		return mav;
	}
	
	@RequestMapping(value = "/saveDomain/{userId}/{goodsId}", method = RequestMethod.POST)
	@ResponseBody
	public boolean saveDomain(@PathVariable Integer userId,@PathVariable String goodsId,User user,HttpServletRequest request)
			throws Exception {
		
		boolean isSuccess = false;
		String userInfoName = "";
		
		Goods goods = goodsService.selectGoodsVoByGoodsId(goodsId);
		String goodsName =  goods.getGoodsName();
		
		User userInfo = (User) request.getSession().getAttribute("userInfo");
		if(userInfo.getUserEmail() != null && !(userInfo.getUserEmail()).isEmpty()){
			userInfoName = userInfo.getUserEmail();
		}else if(userInfo.getUserTel() != null){
			userInfoName = userInfo.getUserTel();
		}
		
		User entity = userService.selectUserInfoByUserId(userId);
		
		/**
		 * 发给客户的邮件  参数分别是  ：  购买套餐的用户名  ，套餐名称，该套餐的管理员账户，该套餐的密码
		 */

		user.setUserEmail(userInfoName);
		taskExecutor.execute(new Runnable(){
		    public void run(){
			    try {
			    	Email email = emailService.selectEmail(28);
			    	String content = email.getEmailContent();
			    	content = content.replace("arg0", user.getUserEmail()).replace("arg1", goodsName).replace("arg2", entity.getUserEmail()).replace("arg3", user.getUserPassword());
			    	EmailUtil.sendMail(user.getPersonEmail(), email.getEmailSubject(), content+email.getEmailSign());
			    	
//			    	EmailUtil.sendMailSetDomainNew(user.getPersonEmail(),new String[]{user.getUserEmail(),goodsName,entity.getUserEmail(),user.getUserPassword()});
			    } catch (Exception e) {
			        e.printStackTrace();
			    }
		    }
	    });
		
		String desPassword = DESUtil.encrypt(user.getUserPassword());
		
		entity.setUserPassword(desPassword);
		entity.setPersonEmail(user.getPersonEmail());
		
		isSuccess = userService.updateUserByKey(entity);
		
		return isSuccess;
	}
	
	
	//================================================================================================================
	/**
	 * 保存用户设置的企业信息 
	 * @param tel
	 * @return 布尔值 true:发送成功 false:发送失败
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/checkDomain", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkDomain(String domain,String userTel,HttpServletRequest request)
			throws Exception {
		boolean domainIsSuccess = false;
		boolean mxIsSuccess = false;
		boolean telIsSuccess = false;
		
		User user = (User) request.getSession().getAttribute("userInfo");
		
		User userByEmail = new User();
		userByEmail.setUserEmail("admin@"+domain);
		userByEmail = userService.loginByEmail(userByEmail);
		
		List<User> userByTelList = new ArrayList<User>();
		userByTelList = (List<User>) userService.TelExists(userTel);
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(userByEmail != null) {
			domainIsSuccess = true;
		}
		if(userByTelList.size() > 0) {
			telIsSuccess = true;
		}
		
		if(user.getRoleId().equals(ROLE_AGENT)){
			mxIsSuccess = false;
		}else{
			mxIsSuccess = CheckEmail.checkEmail("admin@"+domain);
		}
		
		map.put("domainIsSuccess", domainIsSuccess);
		map.put("mxIsSuccess", mxIsSuccess);
		map.put("telIsSuccess", telIsSuccess);
		return map;
	}
	
	/**
	 * 保存用户设置的企业信息 
	 * @param tel
	 * @return 布尔值 true:发送成功 false:发送失败
	 */
	@RequestMapping(value = "/checkCompanyName", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkCompanyName(String companyName,HttpServletRequest request)
			throws Exception {
		boolean companyNameIsSuccess = false;
		
		List<User> user = userService.selectUserByBelongCompanyName(companyName);
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(user.size() > 0 ) {
			companyNameIsSuccess = true;
		}
		map.put("companyNameIsSuccess", companyNameIsSuccess);
		return map;
	}
	
	/**
	 * 保存用户设置的企业信息 
	 * @param user
	 * @return 布尔值 true:发送成功 false:发送失败
	 */
	@RequestMapping(value = "/saveDomainInfo", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveDomainInfo(User user,HttpServletRequest request)
			throws Exception {
		boolean isSuccess = false;
		
		User entity = (User)request.getSession().getAttribute("userInfo");
		String domainLevel = request.getParameter("domainLevel");
		
		user.setUserEmail("admin@"+user.getCompanyDomainName());
		user.setBoundTel(user.getUserTel());
		user.setCompanyDomainName(domainLevel+user.getCompanyDomainName());
		user.setUserValid("0");
		user.setLastLoginTime(new Date());
		user.setAccountMoney(0.00);
		user.setInvoiceMoney(0.00);
		user.setApprove("1");
		user.setUserMessageNum(0);
		user.setAddTime(new Date());
		user.setIsLive("0");
		user.setIsYun("0");
		user.setRoleId(ROLE_COMPANY);
		user.setParentId(entity.getUserId());
		user.setLoginNumber("0");
		
		isSuccess = userService.insertUser(user);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("isSuccess", isSuccess);
		map.put("userId", user.getUserId());
		
		return map;
	}
	
	/**
	 * 向管理员账户发送密码
	 * @param orderId
	 * @return 布尔值 true:发送成功 false:发送失败
	 */
	@RequestMapping(value = "/sendMail", method = RequestMethod.POST)
	@ResponseBody
	public boolean sendMail(HttpServletRequest request) throws Exception {
		
		boolean isSuccess = false;
		Integer orderId = Integer.valueOf(request.getParameter("orderId"));
		OrderVo order = orderService.selectOrderVoByOrderId(orderId);
		String userInfoName = "";
		
		User userInfo = (User) request.getSession().getAttribute("userInfo");
		if(userInfo.getUserEmail() != null && !(userInfo.getUserEmail()).isEmpty()){
			userInfoName = userInfo.getUserEmail();
		}else if(userInfo.getUserTel() != null){
			userInfoName = userInfo.getUserTel();
		}
		
		User entity = userService.selectUserInfoByUserId(order.getUserId());
		entity.setUserPassword(DESUtil.decrypt(entity.getUserPassword()));
		
		/**
		 * 发给客户的邮件  参数分别是  ：  购买套餐的用户名  ，套餐名称，该套餐的管理员账户，该套餐的密码
		 */
		Email email = emailService.selectEmail(28);
    	String content = email.getEmailContent();
    	content = content.replace("arg0", userInfoName).replace("arg1", order.getGoodsName()).replace("arg2", entity.getUserEmail()).replace("arg3", entity.getUserPassword());
    	isSuccess = EmailUtil.sendMail(entity.getPersonEmail(), email.getEmailSubject(), content+email.getEmailSign());
    	
//		isSuccess = EmailUtil.sendMailSetDomainNew(entity.getPersonEmail(),new String[]{userInfoName,order.getGoodsName(),entity.getUserEmail(),entity.getUserPassword()});
		
		return isSuccess;
	}
}
